from tagsupport import TagBuilder
import sys

class TagError(Exception):
	def __init__(self, message):
		self.message = message
		
	def __str__(self):
		return self.message
		
class TagFactory(object):
	def Create(name, attrs):
		tagtype = TagBuilder.CLOSABLE
		name = name.strip()
		if name in ('img','space', 'hr'):
			tagtype = TagBuilder.ONELINE
		elif name == 'document':
			raise TagError,"document tag must be closed inline"
		return PmlTag(name,dict(attrs),tagtype)
	Create = staticmethod(Create)

class PmlTag(object):
	def __init__(self, name, attrs, tagtype=TagBuilder.CLOSABLE):
		self.contentained_elements = []
		if name == 'p' : name = 'para'
		self._name = name
		self._attrs = attrs
		self._type = tagtype
		
	def add(self, object):
		self.contentained_elements.append(object)
			
	def name(self):
		return (self._name == 'para') and 'p' or self._name
			
	def __str__(self):
		"""Returns the content of the tag as a string"""
		rstr = TagBuilder.rebuild_tag(self._name, self._attrs, self._type)
		for i in self.contentained_elements:
			rstr+=str(i)
		rstr+=TagBuilder.rebuild_closure(self._name, self._type)
		return rstr
		
	def generateObject(self, backend, container):
		"""Generates its content and appends it to container"""
		if self._name == 'MAIN': current_object = container
		else: current_object = backend.ObjectFactory.Create(self._name, self._attrs)
			
		for i in self.contentained_elements:
			if type(i) == type(''):
				current_object.append(i)
			elif type(i) == type(self):
				i.generateObject(backend, current_object)
			else: 
				print sys.stderr,"WARNING: Unknown object type",type(i)
	
		if self._name != 'MAIN':
			container.append(current_object)